package cn.wzptsoft.mall.service.Impl;

import cn.wzptsoft.mall.aspect.AutoFull;
import cn.wzptsoft.mall.aspect.OperationType;
import cn.wzptsoft.mall.mapper.UserMapper;
import cn.wzptsoft.mall.pojo.LoginUser;
import cn.wzptsoft.mall.pojo.User;
import cn.wzptsoft.mall.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class IUserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    public PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @AutoFull(value = OperationType.INSERT)
    public void saveUser(User user) {
        String password = user.getPassword();
        user.setPassword(passwordEncoder.encode(password));
        save(user);
    }




    @Override
    public Integer login(String username, String password) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        SecurityContextHolder.getContext().setAuthentication(authenticate);
        //获取用户信息
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        //获取id
        Integer id= loginUser.getUser().getId();
        //用户信息对象转化为json字符串
        String json = JSONObject.toJSONString(loginUser);
        System.out.println("-**-*-*-*缓存用户id"+id);
        //以id为键，存入json格式的用户信息
        redisTemplate.opsForValue().set(String.valueOf(id),json);

        return id;
    }

    @Override
    public void loginout() {
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser)authentication.getPrincipal();
        try {
            redisTemplate.delete(String.valueOf(principal.getUser().getId()));
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("退出失败");
        }

    }
}
